package com.blb.thread;

import java.util.concurrent.*;

public class SemaphoneDemo {

    public static void main(String[] args) {

        //创建信号量 参数1 信号量值 参数2 是否公平锁（公平锁，先等待获得锁几率更大，非公平锁，都一样）
        Semaphore semaphore = new Semaphore(3);
        //创建线程池
        int poolSize = Runtime.getRuntime().availableProcessors() * 2;
        ExecutorService pool = new ThreadPoolExecutor(poolSize,poolSize,0, TimeUnit.SECONDS,new LinkedBlockingQueue<>());

        for (int i = 0; i < 100; i++) {
            // 执行任务
            int finalI = i;
            pool.execute(() -> {
                //申请信号量 信号量-1
                try {
                    semaphore.acquire(3);
                    System.out.println("当前信号量是：" + semaphore.availablePermits());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "-->" + finalI);
                //释放信号量 信号量+1
                semaphore.release(3);
            });
        }

        pool.shutdown();
    }
}
